package com.example.roomtest

import android.os.Bundle
import android.widget.FrameLayout
import androidx.appcompat.app.AppCompatActivity
import com.google.android.material.appbar.AppBarLayout.OnOffsetChangedListener
import kotlinx.android.synthetic.main.activity_scrolling.*


class ScrollingActivity : AppCompatActivity() {




    private var totalHeight //总高度
            = 0f
    private var toolBarHeight //toolBar高度
            = 0f
    private var offSetHeight //总高度 -  toolBar高度  布局位移值
            = 0f
    private var llHeight //搜索框高度
            = 0

    private var llHeightOffScale //高度差比值
            = 0f
    private var llOffDistance:Int //距离差
            = 0
    private var llOffDistanceScale //距离差比值
            = 0f
    private var params: FrameLayout.LayoutParams? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_scrolling)
        bac.alpha = 0f;
        totalHeight = resources.getDimension(R.dimen.app_bar_height);
        toolBarHeight = resources.getDimension(R.dimen.tool_bar_height);
        offSetHeight = totalHeight - toolBarHeight;

        app_bar.addOnOffsetChangedListener(OnOffsetChangedListener { appBarLayout, verticalOffset -> //第一次进入获取高度，以及差值 高度差比值
            if (llHeight === 0) {
                llHeight = ll.measuredHeight
                params = ll.layoutParams as FrameLayout.LayoutParams

                //算出高度偏移量比值  相对与llHeight
                llHeightOffScale = 1.0f - toolBarHeight / llHeight

                //得到滑动差值 就是布局marginTop
                llOffDistance = params!!.topMargin
                //得到滑动比值
                llOffDistanceScale = llOffDistance / offSetHeight
            }

            //滑动一次 得到渐变缩放值
            val alphaScale = -verticalOffset / offSetHeight

            //获取高度缩放值
            val llHeightScale: Float =
                1.0f - llHeightOffScale * (-verticalOffset / offSetHeight)
            //计算maigintop值
            val distance: Float = llOffDistance - -verticalOffset * llOffDistanceScale
            image.alpha = 1.0f - alphaScale
            bac.alpha = alphaScale
            params?.height = (llHeight * llHeightScale).toInt()
            params?.setMargins(0, distance.toInt(), 0, 0)
            fl.requestLayout()
        })
    }
}